package com.pzh.logistics.service.impl;

import com.pzh.logistics.common.constant.OrderConstant;
import com.pzh.logistics.exception.GlobalException;
import com.pzh.logistics.exception.ResultEnum;
import com.pzh.logistics.mbg.mapper.*;
import com.pzh.logistics.mbg.model.*;
import com.pzh.logistics.pojo.VO.OrderVO;
import com.pzh.logistics.service.AddressService;
import com.pzh.logistics.service.CollectionService;
import com.pzh.logistics.service.OrderService;
import com.pzh.logistics.util.DozerUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Autowired
    private AddressService addressService;

    @Autowired
    private CollectionService collectionService;

    @Resource
    private CourierMapper courierMapper;

    @Resource
    private TransitMapper transitMapper;

    @Resource
    private CollectionMapper collectionMapper;

    @Resource
    private TransitOrderMapper orderMapper;

    @Resource
    private AddressMapper addressMapper;

    @Resource
    private StationMapper stationMapper;

    @Override
    @Transactional
    public OrderVO placeOrder(TransitOrder form) {
        //配置新订单默认状态，插入新订单
        form.setIspay(OrderConstant.N);
        form.setState(OrderConstant.PLACE);
        orderMapper.insert(form);

        Integer id = form.getOrderId();
        TransitOrder transitOrder = orderMapper.selectByPrimaryKey(id);

        OrderVO orderVO = new OrderVO();
        DozerUtil.transfor(form, orderVO);
        orderVO.setShipper(addressService.findByAddressId(transitOrder.getShipperId()));
        orderVO.setRecipient(addressService.findByAddressId(transitOrder.getRecipientId()));

        //TODO 补充快递员id:shipperId所在站点
        // - 分配给 站点所属（union）最少单量（count）的快递员
        Collection collection = new Collection();
        collection.setOrderId(transitOrder.getOrderId());
        collection.setCourierId(orderMapper.distributeCourierCollect(
                transitOrder.getShipperId(), OrderConstant.NOT_COLLECT_NUM));
        collection.setIsCollection(OrderConstant.N_C);
        collectionService.insert(collection);
        log.info("【快递员分配】 "+collection.toString());
        Transit transit = new Transit();
        transit.setOrderId(id);
        transit.setTransitOrder(OrderConstant.START_NUM);
        transit.setIsFinish(OrderConstant.N_C);
        transit.setRemarks(OrderConstant.PLACE);
        transitMapper.insert(transit);
        log.info("【transit分配】 "+transit.toString());
        return orderVO;
    }

    @Override
    @Transactional
    public int senderPay(Integer orderId, Integer userId) {
        TransitOrder transitOrder = findByOrderId(orderId);
        if (transitOrder == null){
            throw new GlobalException(ResultEnum.ORDER_NOT_EXIST);
        }
        if (OrderConstant.Y.equals(transitOrder.getIspay())){
            throw new GlobalException(ResultEnum.ORDER_HAS_PAID);
        }

        if(OrderConstant.SHIPPMENT_PAY.equals(transitOrder.getPaymentMethod())
                && userId.equals(transitOrder.getUserId())){
            orderMapper.pay(transitOrder.getOrderId(), OrderConstant.Y);
            return 1;
        }
        throw new GlobalException(ResultEnum.UNKNOW_ERROR);
    }

    @Override
    @Transactional
    public int recipientPay(Integer orderId) {
        TransitOrder transitOrder = orderMapper.selectByPrimaryKey(orderId);
        if (transitOrder == null){
            throw new GlobalException(ResultEnum.ORDER_NOT_EXIST);
        }
        if (OrderConstant.Y.equals(transitOrder.getIspay())){
            throw new GlobalException(ResultEnum.ORDER_HAS_PAID);
        }
        orderMapper.pay(orderId, OrderConstant.Y);
        return 0;
    }

    @Override
    @Transactional
    public int collectConfirm(Integer orderId, Integer courierId) {
        TransitOrder transitOrder = orderMapper.selectByPrimaryKey(orderId);
        if (!OrderConstant.Y.equals(transitOrder.getIspay())){
            throw new GlobalException(ResultEnum.ORDER_NOT_PAID);
        }
        collectionService.updateState(orderId, OrderConstant.Y_C);
        orderMapper.updateStateByOrderId(orderId, OrderConstant.COLLECTED);

        //更新transit
        Transit old = getNewestTransit(orderId);

        Transit newTransit = createTransit(old);
        Courier courier = courierMapper.selectByPrimaryKey(courierId);
        newTransit.setTargetId(courier.getStationId());
        transitMapper.insert(newTransit);
        return 0;
    }

    @Override
    @Transactional
    public int signConfirm(Integer orderId) {
        TransitOrder transitOrder = orderMapper.selectByPrimaryKey(orderId);
        if (OrderConstant.N.equals(transitOrder.getIspay())){
            throw new GlobalException(ResultEnum.ORDER_NOT_PAID);
        }
        orderMapper.updateStateByOrderId(orderId, OrderConstant.SIGNED);
        return 0;
    }

    @Override
    @Transactional
    public int orderCompleteConfirm(Integer orderId, Integer userId) {
        TransitOrder transitOrder = orderMapper.selectByPrimaryKey(orderId);

        if (transitOrder == null){
            throw new GlobalException(ResultEnum.ORDER_NOT_EXIST);
        }

        if (!userId.equals(transitOrder.getUserId())){
            throw new GlobalException(ResultEnum.CHECK_ULTRA_VIRES);
        }
        orderMapper.updateStateByOrderId(transitOrder.getOrderId(), OrderConstant.CONFIRM);
        return 0;
    }

    @Override
    @Transactional
    public int arriveStationConfirm(List<Integer> idList, Integer stationId) {
        Station curStation = stationMapper.selectByPrimaryKey(stationId);
        //TODO 站点接受转发到上级
        idList.forEach(id -> {
            orderMapper.updateStateByOrderId(id, OrderConstant.ARRIVED);

            Transit old = getNewestTransit(id);
            Transit newTransit = createTransit(old);
            newTransit.setStartId(old.getTransitId());

            //1. 同地区不需要转发
            //2. 不同地区需要转发

            //--- 1. 获取订单地址
            Address targetAddress = addressMapper.selectRecipientAddressByOrderId(id);

            //--- 2. 对比当前地址
            // ----- 2.1 省不同，向上级转运
            if (!curStation.getProvince().equals(targetAddress.getProvince())) {
                // ----- 2.1.1 不是中心则向上转运
                if (OrderConstant.NONE_CENTER.equals(curStation.getCenterId())){
                    newTransit.setTargetId(curStation.getCenterId());
                } else {
                    // ----- 2.1.2 不同省份间的转运
                    Station targetStation = stationMapper.findByProvinceCenter(
                            targetAddress.getProvince(), OrderConstant.NONE_CENTER
                    );
                    newTransit.setTargetId(targetStation.getStationId());
                }

            } else if (curStation.getCity().equals(targetAddress.getCity())){
                //给快递员派送
                TransitOrder transitOrder = orderMapper.selectByPrimaryKey(id);
                orderMapper.updateStateByOrderId(id, OrderConstant.DELIVER);
                Integer courierId = orderMapper.distributeCourierCollect(
                        transitOrder.getShipperId(), OrderConstant.NOT_DELIVER_NUM);
                newTransit.setTargetId(transitOrder.getShipperId());

                Collection collection = new Collection();
                collection.setOrderId(id);
                collection.setIsCollection(OrderConstant.DELIVER_NUM);
                collection.setCourierId(courierId);
                collectionMapper.insert(collection);
            } else {
                //给对应区站点
                Station targetStation = stationMapper.findByProvinceAndCityStation(
                        targetAddress.getProvince(), targetAddress.getCity()
                );
                newTransit.setTargetId(targetStation.getStationId());
            }
            newTransit.setRemarks(OrderConstant.TRANSIT);
            transitMapper.insert(newTransit);
        });

        return 0;
    }


    @Override
    public List<TransitOrder> findByUserId(Integer userId) {
        return orderMapper.findByUserId(userId);
    }

    @Override
    public TransitOrder findByOrderId(Integer orderId) {
        return  orderMapper.selectByPrimaryKey(orderId);
    }

    public Transit getNewestTransit(Integer orderId){
        Transit transit = transitMapper.selectTransitByOrderIdAndIsFinish(orderId, OrderConstant.N_C);
        //更新旧状态
        transit.setIsFinish(OrderConstant.Y_C);
        transitMapper.updateByPrimaryKey(transit);
        return transit;
    }

    public Transit createTransit(Transit old){
        Transit newTransit = new Transit();
        newTransit.setIsFinish(OrderConstant.N_C);
        newTransit.setOrderId(old.getOrderId());
        newTransit.setTransitOrder(old.getTransitOrder() + 1);
        return newTransit;
    }

    @Override
    public List<Transit> orderHistory(Integer orderId) {
        List<Transit> transits = transitMapper.selectTransitByOrderId(orderId);
        return null;
    }
}
